/**
 * 文档智能摘要工具 - 主页JavaScript
 * 处理文本输入、文件上传和摘要生成功能
 */

// 等待DOM加载完成
document.addEventListener('DOMContentLoaded', function() {
    // 初始化表单处理
    initTextForm();
    initFileForm();
    
    // 初始化范围滑块
    initRangeSliders();
    
    // 初始化复制和保存按钮
    initResultButtons();
});

/**
 * 初始化文本输入表单
 */
function initTextForm() {
    const form = document.getElementById('textForm');
    if (!form) return;
    
    form.addEventListener('submit', async function(e) {
        e.preventDefault();
        
        const text = document.getElementById('textContent').value.trim();
        if (!text) {
            showError('请输入要生成摘要的文本');
            return;
        }
        
        const ratio = parseFloat(document.getElementById('textRatio').value) / 100;
        const algorithm = document.getElementById('textAlgorithm').value;
        
        await generateSummary({
            type: 'text',
            content: text,
            ratio,
            algorithm
        });
    });
}

/**
 * 初始化文件上传表单
 */
function initFileForm() {
    const form = document.getElementById('fileForm');
    if (!form) return;
    
    form.addEventListener('submit', async function(e) {
        e.preventDefault();
        
        const fileInput = document.getElementById('fileUpload');
        const file = fileInput.files[0];
        
        if (!file) {
            showError('请选择要上传的文件');
            return;
        }
        
        const ratio = parseFloat(document.getElementById('fileRatio').value) / 100;
        const algorithm = document.getElementById('fileAlgorithm').value;
        
        // 创建FormData对象
        const formData = new FormData();
        formData.append('file', file);
        formData.append('ratio', ratio);
        formData.append('algorithm', algorithm);
        
        await generateSummary({
            type: 'file',
            formData
        });
    });
}

/**
 * 初始化范围滑块
 */
function initRangeSliders() {
    // 文本输入的比例滑块
    const textRatio = document.getElementById('textRatio');
    const textRatioValue = document.getElementById('textRatioValue');
    if (textRatio && textRatioValue) {
        textRatio.addEventListener('input', function() {
            textRatioValue.textContent = this.value + '%';
        });
    }
    
    // 文件上传的比例滑块
    const fileRatio = document.getElementById('fileRatio');
    const fileRatioValue = document.getElementById('fileRatioValue');
    if (fileRatio && fileRatioValue) {
        fileRatio.addEventListener('input', function() {
            fileRatioValue.textContent = this.value + '%';
        });
    }
}

/**
 * 初始化结果按钮
 */
function initResultButtons() {
    // 复制结果按钮
    const copyButton = document.getElementById('copyResult');
    if (copyButton) {
        copyButton.addEventListener('click', async function() {
            const summaryText = document.getElementById('summaryResult').textContent;
            const success = await copyToClipboard(summaryText);
            
            if (success) {
                showSuccess('摘要已复制到剪贴板');
            } else {
                showError('复制失败，请手动复制');
            }
        });
    }
    
    // 保存结果按钮
    const saveButton = document.getElementById('saveResult');
    if (saveButton) {
        saveButton.addEventListener('click', async function() {
            const summaryResult = document.getElementById('summaryResult').textContent;
            const keywordsResult = Array.from(document.getElementById('keywordsResult').children)
                .map(badge => badge.textContent);
            
            await saveToHistory({
                summary: summaryResult,
                keywords: keywordsResult,
                original: document.getElementById('textContent')?.value || '文件上传',
                source: document.getElementById('fileUpload')?.files[0]?.name || '直接输入',
                ratio: parseFloat(document.getElementById('textRatio').value || document.getElementById('fileRatio').value) / 100,
                algorithm: document.getElementById('textAlgorithm').value || document.getElementById('fileAlgorithm').value
            });
        });
    }
}

/**
 * 生成摘要
 * @param {Object} params - 生成摘要的参数
 */
async function generateSummary(params) {
    // 显示加载指示器
    const loadingIndicator = document.getElementById('loadingIndicator');
    const resultCard = document.getElementById('resultCard');
    const errorAlert = document.getElementById('errorAlert');
    
    loadingIndicator.style.display = 'block';
    resultCard.style.display = 'none';
    errorAlert.style.display = 'none';
    
    try {
        let response;
        
        if (params.type === 'text') {
            // 发送文本摘要请求
            response = await fetch('/api/summarize/text', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    text: params.content,
                    ratio: params.ratio,
                    algorithm: params.algorithm
                })
            });
        } else {
            // 发送文件摘要请求
            response = await fetch('/api/summarize/file', {
                method: 'POST',
                body: params.formData
            });
        }
        
        const data = await response.json();
        
        if (!response.ok) {
            throw new Error(data.error || '生成摘要失败');
        }
        
        if (data.success) {
            displayResults(data);
        } else {
            throw new Error(data.error || '生成摘要失败');
        }
    } catch (error) {
        console.error('生成摘要错误:', error);
        showError(error.message);
    } finally {
        loadingIndicator.style.display = 'none';
    }
}

/**
 * 显示摘要结果
 * @param {Object} data - 摘要结果数据
 */
function displayResults(data) {
    const resultCard = document.getElementById('resultCard');
    const summaryResult = document.getElementById('summaryResult');
    const keywordsResult = document.getElementById('keywordsResult');
    
    // 显示摘要
    summaryResult.textContent = data.summary;
    
    // 显示关键词
    keywordsResult.innerHTML = '';
    data.keywords.forEach(keyword => {
        keywordsResult.appendChild(createKeywordBadge(keyword));
    });
    
    // 显示结果卡片
    resultCard.style.display = 'block';
    
    // 滚动到结果区域
    resultCard.scrollIntoView({ behavior: 'smooth' });
}

/**
 * 保存到历史记录
 * @param {Object} data - 要保存的数据
 */
async function saveToHistory(data) {
    try {
        const response = await fetch('/api/history', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(data)
        });
        
        const result = await response.json();
        
        if (result.success) {
            showSuccess('已保存到历史记录');
        } else {
            throw new Error(result.error || '保存失败');
        }
    } catch (error) {
        console.error('保存历史记录错误:', error);
        showError(error.message);
    }
}